import { createSlice } from '@reduxjs/toolkit';

interface IUseInfo {
    nickname: string;
    uid: string
}
interface AuthState {
    token: string | null;
    layoutPermissions: string[]; // 路由权限
    btnPermissions: string[]; // 按钮权限
    isLoading: boolean;
    error: string | null;
    useInfo: IUseInfo | null;
}

const getLocalStorageData = (key: string) => {
    const item = localStorage.getItem(key);
    return item ? JSON.parse(item) : null;
}
const initialState: AuthState = {
    token: localStorage.getItem('token') || null,
    useInfo: getLocalStorageData('userInfo'),
    layoutPermissions: [],
    btnPermissions: [],
    isLoading: false,
    error: null,
}

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setToken(state, action) {
            state.token = action.payload;
            localStorage.setItem('token', action.payload);
        },
        setUseInfo(state, action) {
            state.useInfo = action.payload;
            localStorage.setItem('userInfo', JSON.stringify(action.payload));
        },
        setLayoutPermissions(state, action) {
            state.layoutPermissions = action.payload;
            state.isLoading = false;
            state.error = null;
        },
        setBtnPermissions(state, action) {
            state.btnPermissions = action.payload;
        },
        setLoading(state) {
            state.isLoading = true;
            state.error = null;
        },
        setError(state, action) {
            state.isLoading = false;
            state.error = action.payload;
        },
        logout(state) {
            state.token = null;
            state.layoutPermissions = [];
            state.useInfo = null;
            localStorage.removeItem('token');
            localStorage.removeItem('useInfo')
        },
    },
})

export const { setToken, setLayoutPermissions, setBtnPermissions, setLoading, setError, logout, setUseInfo } = authSlice.actions
export default authSlice.reducer